import WebUploader from 'webuploader/dist/webuploader.js';

export default function(app) {
	app.service('fileUploaderService', fileUploaderService);

	function fileUploaderService($http) {
		'ngInject';

		this.defaultOpt = {
			auto: true,
			swf: 'http://cdn.staticfile.org/webuploader/0.1.0/Uploader.swf',
			duplicate: true,
			fileNumLimit: 50,
			accept: {
		    title: 'Images',
		    extensions: 'gif,jpg,jpeg,bmp,png',
		    mimeTypes: 'image/*'
			},
		};

		this.initUploader = (opt, fileQueuedCB, uploadSuccessCB, uploadErrorCB) => {
			let uploader = WebUploader.create(angular.extend(this.defaultOpt, opt));
			// 上传成功回调函数
			if (fileQueuedCB) {
				if (!angular.isFunction(fileQueuedCB)){
					console.error('fileQueued callback is not a function');
					return false;
				}
				uploader.on('fileQueued', fileQueuedCB);
			}
			if (uploadSuccessCB) {
				if (!angular.isFunction(uploadSuccessCB)){
					console.error('uploadSuccess callback is not a function');
					return false;
				}
				uploader.on('uploadSuccess', uploadSuccessCB);
			}
			if (uploadErrorCB) {
				if (!angular.isFunction(uploadErrorCB)){
					console.error('uploadError callback is not a function');
					return false;
				}
				uploader.on('uploadError', uploadErrorCB);
			}
			return uploader;
		};
	}
};